package com.droidnova.android.games.vortex;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Layout;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class Vortex extends Activity implements ColorPickerDialog.OnColorChangedListener{
	//color variables
	private static final int DIALOG_TEXT_ENTRY = 7;
	private static final int DIALOG_FILE_ENTRY = 8;
	private static final int DIALOG_FILE_ENTRY1 = 9;  
	private static final int DIALOG_SLICE_ENTRY = 6;
	private String[] mFileList;
	private File mPath = new File(Environment.getExternalStorageDirectory() + "/");
	private String mChosenFile;
	private static final String FTYPE = ".txt"; 
	private static final String BRIGHTNESS_PREFERENCE_KEY = "brightness";
	private static final String COLOR_PREFERENCE_KEY = "color";
	int colorval=0;
	int colorval1=0;
	//TableLayout.LayoutParams rowInTableLp;
	TableRow.LayoutParams rowInTableLp;
	//slice reset
	int slice_flag=0;
	
	//range to calculate earray text
	float range=0.0f;
	InputMethodManager imm;

	//static int a = 2;
	private export export1;
	private VortexRenderer _VortexRenderer;
	private lines linecube1;
	float _pcolors[] ,_pvertices[],_pintensity[];
	points1 pointcube1;

	int _noVertices;
	//Intent i;
	Intent myIntent;
	EditText text;

	int no;
	int r =20;

	//dynamic table variables
	TableLayout tl,t3;
	TableRow rowtext,rowtext1,rowtext2;
	int _levels=4;
	TextView barray[],init_barray[];
	CheckBox ckarray[], init_ckarray[],ckarrayzero;
	EditText earray[], init_earray[];
	TextView earrayzero,barrayzero;
	TableRow.LayoutParams params ,params1 ,params2;
	
	//reset
	//Copy arrays for reset
	float[] copy_c,copy_v ,copy_2c,copy_2v;
	int copy_noVertices ,copy_2noVertices;
	float copy_xmax,copy_ymax,copy_zmax ,copy_max;
	//slice
	float dec_value=0.0f;

	//initial table
	int init_no= 5;
	
	//alert dialog
	int which1=0;
	
	
	//slice
	TextView slice2;
	EditText ed1;
	
	//dialog slice
	CheckBox ck4;
	String x;
	//camera flag
	int camera_flag=0;
	//reload flag
	int reload_eflag=0;
	boolean reload=false;
	
	//variables for surface

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		//NUMPER PICKER DIALOG
		case DIALOG_TEXT_ENTRY:
			LayoutInflater factory = LayoutInflater.from(this);
			//final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry1, null);
			final View textEntryView = factory.inflate(R.layout.main1, null);
			return new AlertDialog.Builder(this)
			.setTitle("Set Number")
			.setView(textEntryView)
			.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					NumberPicker np = (NumberPicker) textEntryView.findViewById(R.id.numpic);
					_levels=np.getCurrent();
					Log.v("getvaluetext","getvaluetext->"+_levels);
					createB(_levels);
					createSurface(_levels);
					/* User clicked OK so do some stuff */
				}
			})
			.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {

					/* User clicked Cancel so do some stuff */
				}
			})
			.create();
			//EXIT DIALOG
		case DIALOG_FILE_ENTRY:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Are you sure you want to exit?")
			.setCancelable(false)
			.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					Vortex.this.finish();
				}
			})
			.setNegativeButton("No", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
			AlertDialog alert = builder.create();
			return alert;
			//FILE PICKER DIALOG
		case DIALOG_FILE_ENTRY1:
			Dialog dialog = null;
			
			AlertDialog.Builder builder1 = new Builder(this);

			builder1.setTitle("Cick on the File to Select");
			if(mFileList == null){
				Log.e("log1", "Showing file picker before loading the file list");

			}
			builder1.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					try
					{
					mChosenFile = mFileList[which1];
					export1.createVC(mChosenFile);
					//set pointcube
					pointcube1.set_pcolors(export1._pcolors);
					pointcube1.set_pvertices(export1._pvertices);
					pointcube1.set_noVertices(export1._noVertices);
					
					//setline cube
                    linecube1.setA1(export1.getMaxXValue(export1._pvertices)) ;
                    linecube1.setB1(export1.getMaxYValue(export1._pvertices)) ;
                    linecube1.setC1(export1.getMaxZValue(export1._pvertices)) ;
                    linecube1.set_pvertices1(linecube1.setvertex(linecube1.getA1(), linecube1.getB1(), linecube1.getC1()));
                    
                    //display changed point cube and line cube
					_VortexRenderer.setPointcube(pointcube1);
					_VortexRenderer.setlinecube(linecube1);
					
					rowtext.removeAllViews();
					rowtext1.removeAllViews();
					rowtext2.removeAllViews();
					createB(4);
					createSurface(4);
					
					copy_c = (float[])export1._pcolors.clone();
		            copy_v =(float[])export1._pvertices.clone();
		            copy_noVertices = export1._noVertices;
		            
		            //copy_2c = (float[])copy_c.clone();
		           // copy_2v =(float[])copy_v.clone();
		           // copy_2noVertices = copy_noVertices;
		            
		            //settings for mintext and maxtext
		            mintext.setText("Min1="+String.valueOf(export1.min_value+" "));
		            maxtext.setText("Min1="+String.valueOf(export1.max_value));
		            range = export1.max_value -export1.min_value;
		            
		            //settings for slice
		            copy_xmax = export1.getMaxXValue(copy_v);
		            copy_ymax = export1.getMaxYValue(copy_v);
		            copy_zmax = export1.getMaxZValue(copy_v);
		            
		            Log.v("copyxmax value initial","CX="+copy_xmax);
		            Log.v("copyxmax value initial","CY="+copy_ymax);
		            Log.v("copyxmax value initial","CZ="+copy_zmax);
		            
		            dec_value=0.1f;
					}
					catch(Exception e)
					{
						e.printStackTrace();
						Toast.makeText(Vortex.this, "Could not load File;Check file format!", Toast.LENGTH_SHORT).show();
					}
				}
			});
			builder1.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
			
			builder1.setSingleChoiceItems(mFileList, -1, new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int whichButton) {
		        	which1=whichButton; 

		        }
		    });

			dialog = builder1.create();
			return dialog;
		case DIALOG_SLICE_ENTRY:
			LayoutInflater sfactory = LayoutInflater.from(this);
			final View sView = sfactory.inflate(R.layout.slicelayout, null);
			return new AlertDialog.Builder(this)
			.setTitle("Slice Settings")
			.setView(sView)
			.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					CheckBox ck1 = (CheckBox)sView.findViewById(R.id.checkBox1);
					CheckBox ck2 = (CheckBox)sView.findViewById(R.id.checkBox2);
					CheckBox ck3 = (CheckBox)sView.findViewById(R.id.checkBox3);
					ck4 = (CheckBox)sView.findViewById(R.id.checkBox4);
					ed1 = (EditText)sView.findViewById(R.id.editText1);
					
					//set slice x,y,z
					if(ck1.isChecked())
					{
						slice2.setEnabled(true);
						slice2.setClickable(true);
						slice2.setText("SliceX");
					}
					else if(ck2.isChecked())
					{
						slice2.setEnabled(true);
						slice2.setClickable(true);
						slice2.setText("SliceY");
					}
					else if(ck3.isChecked())
					{
						slice2.setEnabled(true);
						slice2.setClickable(true);
						slice2.setText("SliceZ");
					}
					else
					{
						slice2.setEnabled(false);
						slice2.setClickable(false);
						slice2.setText("");
					}
					

				}
			})
			.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {

				}
			})
			.create();

		}

		return null;
	}

	private Context context;
	int[] bcolor = new int[11];
	LinearLayout t2;
	TextView mintext,maxtext;
	TextView Nocolor;
	//ON CREATE METHOD
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		export1 = new export(this,null);
		_pcolors = export1._pcolors;
		_pvertices = export1._pvertices;
		_noVertices = export1._noVertices;
		_pintensity = export1._intensity;
		pointcube1 = new points1(export1._pcolors,export1._pvertices,export1._noVertices);
		//initial copy array for reset
		copy_c = (float[])export1._pcolors.clone();
        copy_v =(float[])export1._pvertices.clone();
        copy_noVertices = export1._noVertices;
      //settings for slice
        copy_xmax = export1.getMaxXValue(copy_v);
        copy_ymax = export1.getMaxYValue(copy_v);
        copy_zmax = export1.getMaxZValue(copy_v);
        dec_value=0.1f;
		Log.v("copyxmax value initial","CX="+copy_xmax);
        Log.v("copyxmax value initial","CY="+copy_ymax);
        Log.v("copyxmax value initial","CZ="+copy_zmax);
        
		linecube1 = new lines(copy_xmax,copy_xmax,copy_zmax);
	
		_VortexRenderer = new VortexRenderer(this , pointcube1,linecube1,camera_flag);
		_VortexRenderer.getHolder().setFormat(PixelFormat.RGBA_8888);

		setContentView(_VortexRenderer);
		
		
		/*//initial copy array for reset
		copy_c = (float[])export1._pcolors.clone();
        copy_v =(float[])export1._pvertices.clone();
        copy_noVertices = export1._noVertices;
      //settings for slice
        copy_xmax = export1.getMaxXValue(copy_c);
        copy_ymax = export1.getMaxYValue(copy_c);
        copy_zmax = export1.getMaxZValue(copy_c);
        dec_value=0.1f;*/
		
        
		
		//initial array values and colors
		final float init_values[] ={0f*(export1.max_value),.25f*(export1.max_value), .50f*(export1.max_value), .75f*(export1.max_value),1.0f*(export1.max_value)};
		//final int init_colors[] ={R.color.Yellow,R.color.Cyan,R.color.Magenta,R.color.White,R.color.Black};
		//Color color = new Color();
		//final int colors[] = {color.BLUE,color.CYAN,color.GREEN,color.RED,color.YELLOW,color.MAGENTA,color.WHITE,color.LTGRAY,Color.rgb(238,130,238),Color.rgb(244,164,96)};
		init_barray = new TextView[init_no];
		init_earray = new EditText[init_no];
		init_ckarray = new CheckBox[init_no];
		final int init_colors[]=  new int[5];
		init_colors[0]= Color.rgb(255,222,173);//Navajo White
		init_colors[1]= Color.rgb(0,0,255); //blue
		init_colors[2]= Color.rgb(0,255,0); //green
		init_colors[3]= Color.rgb(225,0,0); //red
		init_colors[4]= Color.rgb(0,0,0); //black
		//default color array
		
		bcolor[0]= Color.rgb(255,222,173);//Navajo White
		bcolor[1]= Color.rgb(0,0,255); //blue
		bcolor[2]= Color.rgb(0,255,0); //green
		bcolor[3]= Color.rgb(225,0,0); //red
		bcolor[4]= Color.rgb(255,255,0); //yellow
		bcolor[5]= Color.rgb(255,105,180); //hotpink
		bcolor[6]=Color.rgb(0,255,255); //cyan
		bcolor[7]=Color.rgb(210,105,30);//chocolate
		bcolor[8]=Color.rgb(160,32,240); //purple
		bcolor[9]=Color.rgb(255,255,255); //white
		bcolor[10]=Color.rgb(0,0,0); //black

		context = this;
		

		//Set Table Layout
		tl = new TableLayout(this);
		
		
		//tl.setStretchAllColumns(true);
		//tl.setShrinkAllColumns(true);
		
		//Set Table Layout
		t3 = new TableLayout(this);
		t3.setStretchAllColumns(true);
		t3.setShrinkAllColumns(true);
	
		
		//Set Linear Layout
		t2 = new LinearLayout(this);
		mintext = new TextView(this);
		mintext.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 9); 
		mintext.setText("Min="+String.valueOf(export1.min_value+" "));
		mintext.setTypeface(null, Typeface.BOLD);

		maxtext = new TextView(this);
		maxtext.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 9); 
		maxtext.setText("Max="+String.valueOf(export1.max_value));
		maxtext.setTypeface(null, Typeface.BOLD);
		t2.addView(mintext);
		t2.addView(maxtext);
		
		//range for setting text for earray
		range = export1.max_value -export1.min_value;
		
		//Set rows for t1
		
		rowtext = new TableRow(this);  
		rowtext1 = new TableRow(this);
		rowtext2 = new TableRow(this);
		
		//set rows for t3
		TableRow first = new TableRow(this);
        
		//File button
		final TextView button4 = new TextView(this);
		button4.setTextColor(getResources().getColor(R.color.Black));
		button4.setText("File");
		button4.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);  
		button4.setGravity(Gravity.CENTER);  
		button4.setTypeface(Typeface.SERIF, Typeface.BOLD);
		button4.setBackgroundResource(R.color.Gray);
		first.addView(button4);
		//OnClick listener for File button
		button4.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				loadFileList();
				showDialog(DIALOG_FILE_ENTRY1);
				//reset slice
				dec_value=0.1f;

			}
		});
		
		
		//reload button
		 final TextView button1 = new TextView(this);
		//button1.setClickable(false);
		button1.setTextColor(getResources().getColor(R.color.Black));
		button1.setText("Reload");	
		button1.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);  
		button1.setGravity(Gravity.CENTER);  
		button1.setTypeface(Typeface.SERIF, Typeface.BOLD);
		button1.setBackgroundResource(R.color.White);
		// Onclick Listener for Reload
		button1.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				createReload();
				/*if(reload==false)
				{
					reload=true;
					button1.setClickable(false);
					createReload();
					reload=false;
					button1.setClickable(true);
				}*/
				
				
			}
		});
		first.addView(button1);
		
		//Number select button
		TextView button = new TextView(this);
		button.setTextColor(getResources().getColor(R.color.Black));
		button.setText("Levels");
		button.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);  
		button.setGravity(Gravity.CENTER);  
		button.setTypeface(Typeface.SERIF, Typeface.BOLD);
		button.setBackgroundResource(R.color.White);
		//Onclick Listener for button
		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				showDialog(DIALOG_TEXT_ENTRY);
				//button1.setClickable(true);

			}
		});
		first.addView(button);

		

		/*//slice button
		final TextView button3 = new TextView(this);
		button3.setTextColor(getResources().getColor(R.color.Black));
		button3.setText("Slice");
		button3.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);  
		button3.setGravity(Gravity.CENTER);  
		button3.setTypeface(Typeface.SERIF, Typeface.BOLD);
		button3.setBackgroundResource(R.color.Gray);
		first.addView(button3);
		//Onclick listener for slice
		button3.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				//recalc();
				//recalc1();
				//recalc2();
				//recalc3();
				//recalc4();
				//recalc5();
				
				//slicex("sliceX");
					recalc6();

			}
		});*/
		
		//camera /rotate button
		
		final TextView tb = new TextView(this);
		tb.setTextColor(getResources().getColor(R.color.Black));
		tb.setText("Rot.On");
		tb.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);  
		tb.setGravity(Gravity.CENTER);  
		tb.setTypeface(Typeface.SERIF, Typeface.BOLD);
		tb.setBackgroundResource(R.color.White);
        first.addView(tb);  
       // camera_flag
        tb.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
			if(camera_flag==0)
			{
				camera_flag=1;
				tb.setText("Rot.Off");
				_VortexRenderer.setCameraflag(camera_flag);
				
			}
			else
			{
				camera_flag=0;
				tb.setText("Rot.On");
				_VortexRenderer.setCameraflag(camera_flag);
			} 

			}
		});
        
		//reset button
		final TextView button2 = new TextView(this);
		button2.setTextColor(getResources().getColor(R.color.Black));
		button2.setText("Reset");
		button2.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);  
		button2.setGravity(Gravity.CENTER);  
		button2.setTypeface(Typeface.SERIF, Typeface.BOLD);
		button2.setBackgroundResource(R.color.Gray);
		first.addView(button2);

		//On click listener for reset
		button2.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				//button1.setClickable(false);
				//init_createB(4);
				rowtext.removeAllViews();
				rowtext1.removeAllViews();
				rowtext2.removeAllViews();
				colorval=0;
				colorval1=0;
				_levels=4;	
				export1._pcolors = (float[])copy_c.clone();
				export1._pvertices = (float[])copy_v.clone();
				export1._noVertices =copy_noVertices; 
				pointcube1.set_pcolors(export1._pcolors);
				pointcube1.set_pvertices(export1._pvertices);
				pointcube1.set_noVertices(export1._noVertices);
				_VortexRenderer.setPointcube(pointcube1);
				createB(_levels);
				createSurface(_levels);
				
				//pointcube1.set_pcolors(copy_c);
				//pointcube1.set_pvertices(copy_v);
				//pointcube1.set_noVertices(copy_noVertices);
				copy_xmax = export1.getMaxXValue(copy_v);
				copy_ymax = export1.getMaxYValue(copy_v);
				copy_zmax = export1.getMaxZValue(copy_v);
				dec_value=0.1f;
				slice_flag=0;

			

			}
		});
		
		
		//slice button
		final TextView slice1 = new TextView(this);
		slice1.setTextColor(getResources().getColor(R.color.Black));
		slice1.setText("Slice.Set");
		slice1.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);  
		slice1.setGravity(Gravity.CENTER);  
		slice1.setTypeface(Typeface.SERIF, Typeface.BOLD);
		slice1.setBackgroundResource(R.color.Gray);
		first.addView(slice1);
		//Onclick listener for slice
		slice1.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				
				showDialog(DIALOG_SLICE_ENTRY);	

			}
		});
		
		//slice button
		slice2 = new TextView(this);
		slice2.setEnabled(false);
		slice2.setClickable(false);
		slice2.setTextColor(getResources().getColor(R.color.Black));
		slice2.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);  
		slice2.setGravity(Gravity.CENTER);  
		slice2.setTypeface(Typeface.SERIF, Typeface.BOLD);
		slice2.setBackgroundResource(R.color.Gray);
		first.addView(slice2);
		//Onclick listener for slice
		slice2.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if(ck4.isChecked())
				{
					//do something
					x = ed1.getText().toString();
					if(x.trim().equalsIgnoreCase("") || x.trim().length()==0)
					{
						Toast.makeText(Vortex.this,
								"Enter an Intensity Value",
								Toast.LENGTH_LONG).show();
					}
					else
					{
						String slicetext = slice2.getText().toString();
						slicex(slicetext);
					}
				}
				else
				{
					//do something
					String slicetext = slice2.getText().toString();
					slicex(slicetext);

				}
				
			}
		});
		
		//Nocolor button
		Nocolor = new TextView(this);
		Nocolor.setText("No Color");
		Nocolor.setTextColor(getResources().getColor(R.color.Black));
		Nocolor.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);  
		Nocolor.setGravity(Gravity.CENTER);  
		Nocolor.setTypeface(Typeface.SERIF, Typeface.BOLD);
		Nocolor.setBackgroundResource(R.color.Gray);
		first.addView(Nocolor);
		//Onclick listener for No color
		Nocolor.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View view) {
				Log.v("reload", "reload");
				int f_reload =0, f_reload1=0;
				//Arrays.fill(export1._pcolors, 0);
				// button1.setBackgroundColor(Integer.parseInt(barray[2].getTag().toString()));
				for(int i=0;i<_levels+1;i++)
				{
					if( earray[i].getText().toString().length() == 0 || earray[i].getText().toString() == "" || (earray[i].getText().toString()).trim().equalsIgnoreCase(""))   
					{  
						f_reload=f_reload+1;

					}
					else if(Float.parseFloat(earray[i].getText().toString()) < 0  || Float.parseFloat(earray[i].getText().toString()) > export1.max_value )

					{ 

						f_reload=f_reload+1;
					}
					/*else if(i<(_levels))
					{
						if(Float.parseFloat(earray[i].getText().toString()) > Float.parseFloat(earray[i+1].getText().toString()))
						{
							f_reload1=f_reload1+1; 
						}
					}
					else if(i==(_levels))
					{
						if(Float.parseFloat(earray[i].getText().toString()) > Float.parseFloat(earrayzero.getText().toString()))
						{
							f_reload1=f_reload1+1;
						}
					}*/
				}

				if(f_reload >0)
				{
					Toast.makeText(Vortex.this,
							"enter a value between "+export1.min_value+ "and"+ export1.max_value,
							Toast.LENGTH_LONG).show();
				}
				else if(f_reload1 >0)
				{
					Toast.makeText(Vortex.this,
							"Please check if values are in Order",
							Toast.LENGTH_LONG).show();
				}
				else
				{
					int count =0;
					for(int k=0;k<export1._noVertices;k++)
					{
						for(int m=0;m<_levels+1;m++)
						{
							int ffff = Integer.parseInt((barray[m].getTag().toString()));
							int red,blue,green,alpha=0;
							float r1=0.0f,g1=0.0f,b1=0.0f,a1=0.0f;
							if(ffff==0)
							{
								red = Color.red(bcolor[m]);
							    blue = Color.blue(bcolor[m]);
							    green = Color.green(bcolor[m]);
							    alpha = Color.alpha(bcolor[m]);
							    
							    r1 = red/255f;
								g1 = green/255f;
								b1 = blue/255f;
								a1 = alpha/255f;
							    
							}
							else
							{	
                            red = Color.red(ffff);
							blue = Color.blue(ffff);
							green = Color.green(ffff);
							alpha = Color.alpha(ffff);
							
							r1 = red/255f;
							g1 = green/255f;
							b1 = blue/255f;
							a1 = alpha/255f;
							}
							if(export1._intensity[k]>Float.parseFloat(earray[m].getText().toString()) &&  export1._intensity[k]<= Float.parseFloat(earray[m+1].getText().toString()))
							{								
								if(ckarray[m].isChecked())
								{
									export1._pcolors[count] = 0.0f;
									export1._pcolors[count+1]=0.0f;
									export1._pcolors[count+2]=0.0f;
									export1._pcolors[count+3] =0.0f;
								}
								else
								{
								export1._pcolors[count] = r1;
								export1._pcolors[count+1]= g1;
								export1._pcolors[count+2]= b1;
								export1._pcolors[count+3] = a1;
								}
							}
							/*if(m==(_levels-1))
							{
								if(export1._intensity[k]>Float.parseFloat(earray[m].getText().toString()) && export1._intensity[k]<= Float.parseFloat(earrayzero.getText().toString()))
								{ 
									if(ckarray[m].isChecked())
									{
										export1._pcolors[count] = 0.0f;
										export1._pcolors[count+1]=0.0f;
										export1._pcolors[count+2]=0.0f;
										export1._pcolors[count+3] =0.0f;
	
									}
									else
									{
									export1._pcolors[count] = r1;
									export1._pcolors[count+1]= g1;
									export1._pcolors[count+2]= b1;
									export1._pcolors[count+3] = a1;
									}
								}
							}
							else
							{

								if(export1._intensity[k]>Float.parseFloat(earray[m].getText().toString()) &&  export1._intensity[k]<= Float.parseFloat(earray[m+1].getText().toString()))
								{								
									if(ckarray[m].isChecked())
									{
										export1._pcolors[count] = 0.0f;
										export1._pcolors[count+1]=0.0f;
										export1._pcolors[count+2]=0.0f;
										export1._pcolors[count+3] =0.0f;
									}
									else
									{
									export1._pcolors[count] = r1;
									export1._pcolors[count+1]= g1;
									export1._pcolors[count+2]= b1;
									export1._pcolors[count+3] = a1;
									}
								}

							}*/

						}


						count=count+4;                  
					}
					pointcube1.set_pcolors(export1._pcolors);
					pointcube1.set_pvertices(export1._pvertices);
					pointcube1.set_noVertices(export1._noVertices);
					
					_VortexRenderer.setPointcube(pointcube1);
					//copy_2c = (float[])export1._pcolors.clone();
		            //copy_2v =(float[])export1._pvertices.clone();
		            //copy_2noVertices = export1._noVertices;
					
					//settings for slice
					copy_xmax = export1.getMaxXValue(copy_v);
					copy_ymax = export1.getMaxYValue(copy_v);
					copy_zmax = export1.getMaxZValue(copy_v);
					dec_value=0.1f;
					slice_flag=0;
				}
			}
			
		});
		
		//Table Layout params
		params1 = new TableRow.LayoutParams(); 
		params1.width=0;
		params = new TableRow.LayoutParams();
		
		rowInTableLp = new TableRow.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		rowInTableLp.weight =0.3f;
		//Create the Initial Color Table Display
		createB(_levels);
		createSurface(_levels);
		/*for(i=0;i<init_no;i++)
		{  
			//textviews in row2
			init_barray[i] = new TextView(this);
			//init_barray[i].setBackgroundResource(init_colors[i]);
			//init_barray[i].setBackgroundResource(bcolor[i]);
			init_barray[i].setBackgroundColor(init_colors[i]);
			//edittexts in row3
			init_earray[i] = new EditText(this);
			init_earray[i].setTextColor(getResources().getColor(R.color.White));
			init_earray[i].setBackgroundResource(R.color.Black);
			init_earray[i].setTextSize(TypedValue.COMPLEX_UNIT_DIP, 7); 
			init_earray[i].setInputType(InputType.TYPE_CLASS_NUMBER);
			init_earray[i].setFilters(new InputFilter[]{new InputFilter.LengthFilter(3)});
			init_earray[i].setGravity(Gravity.LEFT);
			init_earray[i].setText(String.valueOf(init_values[i]));
			init_earray[i].setMaxLines(1);	
			//add to row
			rowtext.addView(init_barray[i],params);	
			rowtext1.addView(init_earray[i],params);
		}
*/

		//add Rows to TableLayout
		
		
		
		
		
		//tl.addView(first);
		t3.addView(first);
		//tl.addView(first);
		tl.addView(rowtext);
		
		tl.addView(rowtext1);
		tl.addView(rowtext2);
		
		t2.setGravity(Gravity.TOP | Gravity.LEFT );
		//t3.setGravity(Gravity.FILL_VERTICAL | Gravity.CENTER);
		t3.setGravity(Gravity.CENTER);
		tl.setGravity(Gravity.CENTER);
		//tl.setGravity(Gravity.BOTTOM | Gravity.CENTER);
	
		LinearLayout layout = new LinearLayout(this);
		layout.setOrientation(LinearLayout.VERTICAL);
		layout.setGravity(Gravity.BOTTOM | Gravity.CENTER);
		layout.addView(t2);
		layout.addView(t3);
		layout.addView(tl);
		/*RelativeLayout layout = new RelativeLayout(this);
		tl.setId(1);
		t2.setId(2);
		t3.setId(3);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.FILL_PARENT);
        lp.addRule(RelativeLayout.BELOW, t3.getId());
        
        RelativeLayout.LayoutParams lr = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.FILL_PARENT);
        lr.addRule(RelativeLayout.BELOW, t3.getId());
		
        layout.setGravity(Gravity.BOTTOM | Gravity.CENTER);
        layout.addView(t3); 
        layout.addView(tl,lp);
        layout.addView(t3, lr);*/
      //  layout.addView(t2,lr);
        
		//this.addContentView(t2,
		//		new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
       
		//this.addContentView(layout,
				//new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
				
				
		// this.addContentView(layout1,
			//		new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		//this.addContentView(t3,
			//new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		//this.addContentView(tl,
				//new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		/*this.addContentView(t2,
				new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));*/
		this.addContentView(layout,
				new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));



		
	}

	//Called to RESET color bar
	/*public void init_createB(TextView init_barray[], EditText init_earray[])
	{	
		rowtext.removeAllViews();
		rowtext1.removeAllViews();
		for(i=0;i<init_no;i++)
		{  			
			//add to row
			rowtext.addView(init_barray[i],params);	
			rowtext1.addView(init_earray[i],params);
		}
	}*/
	/*public void init_createB(int value)
	{	
		
	}*/
	
	
	
	//Called to RESET renderer

	//Called to CUSTOMIZE COLOR
	int i;
	public void createB(int no)
	{
		
		int size = 8; //text size
		rowtext.removeAllViews();
		rowtext1.removeAllViews();
		rowtext2.removeAllViews();
		barray = new TextView[no+1];
		earray = new EditText[no+1];
		ckarray = new CheckBox[no+1];  
	    float range1 = range/no;
	    float erange=0.0f;
		int noo = no+1;	
		for(i=0;i<noo;i++)
		{  
			
			erange = export1.min_value + (i*range1);
			//textviews in row2
			barray[i] = new TextView(this);
			//barray[i].setWidth(rowtext1.getWidth()/(no+1));
			barray[i].setWidth(0);
			barray[i].setHeight(5);
			//barray.[i].setWidth(30);
			//barray[i].setBackgroundResource(R.color.Blue);
			//barray[i].setBackgroundResource(bcolor[i]);
			
			barray[i].setBackgroundColor(bcolor[i]);
			barray[i].setId(i);
			barray[i].setTag(colorval);
			//edittexts in row3
			earray[i] = new EditText(this);
			earray[i].setPadding(0, 0, 0, 0);
			
			//earray[i].setId(i+10);
			earray[i].setTextColor(getResources().getColor(R.color.White));
			earray[i].setBackgroundResource(R.color.Black);
			earray[i].setTextSize(TypedValue.COMPLEX_UNIT_DIP, size); 
			earray[i].setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
			//InputFilter FilterArray = new InputFilter[1];
			//FilterArray[0] = new InputFilter.LengthFilter(3);
			//earray[i].setFilters(FilterArray);
			earray[i].setFilters(new InputFilter[]{new InputFilter.LengthFilter(5)});
			earray[i].setGravity(Gravity.LEFT |Gravity.TOP);
			earray[i].setText(String.valueOf(erange));
			earray[i].setMaxLines(1);
			//do not allow soft-keyboard to show
		/*	earray[i].setOnTouchListener(new View.OnTouchListener()
			{

				@Override
				public boolean onTouch(View arg0, MotionEvent arg1) {
					// TODO Auto-generated method stub
					return true;
				} 
			
			});*/
			
			//checkbox
			ckarray[i] = new CheckBox(this);  
			ckarray[i].setButtonDrawable(R.drawable.checkbox_selector); 
			ckarray[i].setPadding(0, 0, 0, 0);
			//add to row
			rowtext.addView(barray[i],rowInTableLp);
			Log.v("barray width","barrray width"+barray[i].getWidth());
			rowtext1.addView(earray[i],rowInTableLp);
			rowtext2.addView(ckarray[i],rowInTableLp);
			if(i==(noo-1))
			{
				barray[i].setBackgroundResource(R.color.Black);
				rowtext2.removeViewInLayout(ckarray[i]);
			}
             //on click listener for color array
			barray[i].setOnClickListener(new View.OnClickListener() 
			{
				public void onClick(View cbutton) 
				{
					Log.v("clicked","clicked");
					int color = PreferenceManager.getDefaultSharedPreferences
					(Vortex.this).getInt(COLOR_PREFERENCE_KEY,Color.WHITE);
					new ColorPickerDialog(Vortex.this, Vortex.this,color).show();
					//barray[cbutton.getId()].setBackgroundColor(colorval);			
					colorval1=cbutton.getId();
				}
			});
		}


	}
	
	
	//Create of ArrayList for triangulation
	Map<Integer,float[]> kMap = new HashMap<Integer,float[]>();
	
   float[] _grouparray;
	public void createSurface(int no)
	{ 
		for(int l=0;l<no;l++)
		{
			ArrayList<Float> grouppts = new ArrayList<Float>();
			for(int m=0;m<export1._intensity.length;m++)
			{
				float ll=Float.parseFloat(earray[l].getText().toString());
				if(l==0)
				{
					ll=ll-1;
				}
				if(export1._intensity[m]>ll &&  export1._intensity[m]<= Float.parseFloat(earray[l+1].getText().toString()))
				{								
					grouppts.add(export1._pvertices[m]);
					grouppts.add(export1._pvertices[m+1]);
					grouppts.add(export1._pvertices[m+2]);			
				}	
			}
			_grouparray = toPrimitiveArray(grouppts);
			 kMap.put(l, _grouparray);

		}
		Log.v("total length","total length="+ export1._pvertices.length);
		for(int n=0;n<no;n++)
		{
			Log.v("map length","map length: "+ n + "="+kMap.get(n).length);
		}
	}
	
	
	//Called during reload
	public void createReload()
	{
		//Reload Start
		
		int f_reload =0, f_reload1=0;
		//Arrays.fill(export1._pcolors, 0);
		// button1.setBackgroundColor(Integer.parseInt(barray[2].getTag().toString()));
		for(int i=0;i<_levels+1;i++)
		{
			if( earray[i].getText().toString().length() == 0 || earray[i].getText().toString() == "" || (earray[i].getText().toString()).trim().equalsIgnoreCase(""))   
			{  
				f_reload=f_reload+1;

			}
			else if(Float.parseFloat(earray[i].getText().toString()) < 0  || Float.parseFloat(earray[i].getText().toString()) > export1.max_value )

			{ 

				f_reload=f_reload+1;
			}
			/*else if(i<(_levels))
			{
				if(Float.parseFloat(earray[i].getText().toString()) > Float.parseFloat(earray[i+1].getText().toString()))
				{
					f_reload1=f_reload1+1; 
				}
			}
			else if(i==(_levels))
			{
				if(Float.parseFloat(earray[i].getText().toString()) == export1.max_value)
				{
					f_reload1=f_reload1+1;
				}
			}*/
		}

		if(f_reload >0)
		{
			Toast.makeText(Vortex.this,
					"enter a value between "+export1.min_value+ "and"+ export1.max_value,
					Toast.LENGTH_LONG).show();
		}
		else if(f_reload1 >0)
		{
			Toast.makeText(Vortex.this,
					"Please check if values are in Order",
					Toast.LENGTH_LONG).show();
		}
		else
		{
			int count =0;
			for(int k=0;k<export1._noVertices;k++)
			{
				for(int m=0;m<_levels+1;m++)
				{
					int ffff = Integer.parseInt((barray[m].getTag().toString()));
					int red,blue,green,alpha=0;
					float r1=0.0f,g1=0.0f,b1=0.0f,a1=0.0f;
					if(ffff==0)
					{
						red = Color.red(bcolor[m]);
					    blue = Color.blue(bcolor[m]);
					    green = Color.green(bcolor[m]);
					    alpha = Color.alpha(bcolor[m]);
					    
					    r1 = red/255f;
						g1 = green/255f;
						b1 = blue/255f;
						a1 = alpha/255f;
					    
					}
					else
					{	
                    red = Color.red(ffff);
					blue = Color.blue(ffff);
					green = Color.green(ffff);
					alpha = Color.alpha(ffff);
					
					r1 = red/255f;
					g1 = green/255f;
					b1 = blue/255f;
					a1 = alpha/255f;
					}
					//checking bounds for min to include minimum value too...
					float ll=Float.parseFloat(earray[m].getText().toString());
					if(m==0)
					{
						ll=ll-1;
					}
					if(export1._intensity[k]>ll &&  export1._intensity[k]<= Float.parseFloat(earray[m+1].getText().toString()))
					{								
						export1._pcolors[count] = r1;
						export1._pcolors[count+1]= g1;
						export1._pcolors[count+2]= b1;
						export1._pcolors[count+3] = a1;
						
					}
					/*if(m==(_levels-1))
					{
						if(export1._intensity[k]>Float.parseFloat(earray[m].getText().toString()) && export1._intensity[k]<= Float.parseFloat(earrayzero.getText().toString()))
						{ 
							export1._pcolors[count] = r1;
							export1._pcolors[count+1]= g1;
							export1._pcolors[count+2]= b1;
							export1._pcolors[count+3] = a1;
						}
					}
					else
					{

						if(export1._intensity[k]>Float.parseFloat(earray[m].getText().toString()) &&  export1._intensity[k]<= Float.parseFloat(earray[m+1].getText().toString()))
						{								
							export1._pcolors[count] = r1;
							export1._pcolors[count+1]= g1;
							export1._pcolors[count+2]= b1;
							export1._pcolors[count+3] = a1;
							
						}

					}*/

				}


				count=count+4;                  
			}
			pointcube1.set_pcolors(export1._pcolors);
			pointcube1.set_pvertices(export1._pvertices);
			pointcube1.set_noVertices(export1._noVertices);
			
			_VortexRenderer.setPointcube(pointcube1);
			//copy_2c = (float[])export1._pcolors.clone();
            //copy_2v =(float[])export1._pvertices.clone();
            //copy_2noVertices = export1._noVertices;
			
			//settings for slice
			copy_xmax = export1.getMaxXValue(copy_v);
			copy_ymax = export1.getMaxYValue(copy_v);
			copy_zmax = export1.getMaxZValue(copy_v);
			dec_value=0.1f;
			slice_flag=0;
			colorval=0;
		}
		//reload ends
	}
	
	
	//Called when color changes
	@Override
	public void colorChanged(int color ) {
		PreferenceManager.getDefaultSharedPreferences(this).edit().putInt(COLOR_PREFERENCE_KEY, color).commit();

		colorval = color;
		barray[colorval1].setBackgroundColor(colorval);
		barray[colorval1].setTag(colorval);
	}

	
	
	ArrayList<Float> pcolorsList = new ArrayList<Float>();
	ArrayList <Float> pverticesList = new ArrayList <Float>();
	float[] newvertices,newpcolors;
	//Called to Slice Surface
	
	String conv_v[] , conv_c[];
	float _rv[] , _rc[],_ri[];
	
	
	
	//slicex ************************************************************************
	int length;
	float varray[];
	float carray[];
	float iarray[];
	
	public void slicex(String slicetext)
	{
		Log.v("slicetext","slicetext="+slicetext); 
		int j=0;
		if(slice_flag>0)
		{
			varray = new float[_rv.length];
			carray = new float[_rc.length];
			iarray = new float[_ri.length];
			varray = (float[])_rv.clone();
			carray = (float[])_rc.clone();
			iarray =(float[])_ri.clone();
		}
		else
		{
			varray = new float[export1._pvertices.length];
			carray =new float[export1._pcolors.length];
			iarray = new float[export1._intensity.length];
			varray = (float[])export1._pvertices.clone();
			carray = (float[])export1._pcolors.clone();
			iarray =(float[])export1._intensity.clone();
		}
		
		if(slicetext == "SliceX")
		{
			Log.v("j loop","j loop");
			j=0;
			copy_max = copy_xmax;
			copy_xmax=copy_xmax-dec_value;
		}
		else if(slicetext == "SliceY")
		{
			j=1;
			copy_max = copy_ymax;
			copy_ymax=copy_ymax-dec_value;
		}
		else if(slicetext == "SliceZ")
		{
			j=2;
			copy_max = copy_zmax;
			copy_zmax=copy_zmax-dec_value;
		}
		
		//export1._pcolors = (float[])copy_c.clone();
		//export1._pvertices = (float[])copy_v.clone();
		//export1._pcolors = (float[])copy_2c.clone();
		//export1._pvertices = (float[])copy_2v.clone();
		
		ArrayList<Float> colors = new ArrayList<Float>();
		ArrayList <Float> vertices = new ArrayList <Float>();
		ArrayList <Float> ivalue = new ArrayList <Float>();
		
		int q=0,q1=0;  
		for(int i =j;i<varray.length;i+=3)
		{
			//q =(i/3+1);
			
			q =((i-j)/3+1);
			
			if(ck4.isChecked())
			{
			
				if(varray[i]<copy_max)
				{
					
					q1=(q-1)*4;
					
					vertices.add(varray[3*(q-1)+0]);
					vertices.add(varray[3*(q-1)+1]);
					vertices.add(varray[3*(q-1)+2]);

					colors.add(carray[q1]);
					colors.add(carray[q1+1]);
					colors.add(carray[q1+2]);
					colors.add(carray[q1+3]);
		            ivalue.add(iarray[q-1]);
				}
				else if(iarray[q-1]>  Float.parseFloat(x))
				{
					q1=(q-1)*4;
					vertices.add(varray[3*(q-1)+0]);
					vertices.add(varray[3*(q-1)+1]);
					vertices.add(varray[3*(q-1)+2]);

					colors.add(carray[q1]);
					colors.add(carray[q1+1]);
					colors.add(carray[q1+2]);
					colors.add(carray[q1+3]);
					ivalue.add(iarray[q-1]);
				}
				
			}
			else
			{
				if(varray[i]<copy_max)
				{
					
					q1=(q-1)*4;
					
					vertices.add(varray[3*(q-1)+0]);
					vertices.add(varray[3*(q-1)+1]);
					vertices.add(varray[3*(q-1)+2]);

					colors.add(carray[q1]);
					colors.add(carray[q1+1]);
					colors.add(carray[q1+2]);
					colors.add(carray[q1+3]);
		            ivalue.add(iarray[q-1]);
				}
			}
	}
		_rv = toPrimitiveArray(vertices);
		_rc = toPrimitiveArray(colors);
		_ri =toPrimitiveArray(ivalue);
		//copy_xmax=copy_xmax-dec_value;
		pointcube1.set_pvertices(_rv);
		pointcube1.set_pcolors(_rc);
		pointcube1.set_noVertices(_rv.length/3);
		_VortexRenderer.setPointcube(pointcube1);	
		slice_flag+=1;
	}
	
	public void recalc6()
	{

		export1._pcolors = (float[])copy_c.clone();
		export1._pvertices = (float[])copy_v.clone();
		ArrayList<Float> colors = new ArrayList<Float>();
		ArrayList <Float> vertices = new ArrayList <Float>();
		
		int q=0,q1=0;  
		for(int i =0;i<export1._pvertices.length;i+=3)
		{
			q =(i/3+1);
			if(export1._pvertices[i]<copy_xmax)
			{
				
				q1=(q-1)*4;
				
				//if(export1._intensity[i]<200)
					
				
				vertices.add(export1._pvertices[i]);
				vertices.add(export1._pvertices[i+1]);
				vertices.add(export1._pvertices[i+2]);

				colors.add(export1._pcolors[q1]);
				colors.add(export1._pcolors[q1+1]);
				colors.add(export1._pcolors[q1+2]);
				colors.add(export1._pcolors[q1+3]);


			}
			else if(export1._intensity[q-1]>200)
			{
				q1=(q-1)*4;
				vertices.add(export1._pvertices[i]);
				vertices.add(export1._pvertices[i+1]);
				vertices.add(export1._pvertices[i+2]);

				colors.add(export1._pcolors[q1]);
				colors.add(export1._pcolors[q1+1]);
				colors.add(export1._pcolors[q1+2]);
				colors.add(export1._pcolors[q1+3]);
			}
		}
		_rv = toPrimitiveArray(vertices);
		_rc = toPrimitiveArray(colors);
		
		copy_xmax=copy_xmax-dec_value;
		pointcube1.set_pvertices(_rv);
		pointcube1.set_pcolors(_rc);
		pointcube1.set_noVertices(_rv.length/3);
		_VortexRenderer.setPointcube(pointcube1);	
	}
	
	
	
	
	//conversion ofstring array to float array	
	public float[] convertStringArraytoFloatArray(String[] _new) throws Exception 
	{
		if (_new != null)
		{
			float floatarray[] = new float[_new.length];
			for (int i = 0; i < _new.length; i++) {
				floatarray[i] = Float.parseFloat(_new[i]);
			}
			return floatarray;
		}
		return null;
	}
	//Convertion from a object to premitive array
	private float[] toPrimitiveArray(final ArrayList<Float> vertexList) {
	    final float[] primitives = new float[vertexList.size()];
	    int index = 0;
	    for (Float object : vertexList) {
	        primitives[index++] = object;
	    }
	    return primitives;
	}
	
	//Called when loading a file
	private void loadFileList(){
		try{
			mPath.mkdirs();
		}
		catch(SecurityException e){
			Log.e("log", "unable to write on the sd card " + e.toString());
		}
		if(mPath.exists()){
			FilenameFilter filter = new FilenameFilter(){
				public boolean accept(File dir, String filename){
					File sel = new File(dir, filename);
					return filename.contains(FTYPE) || sel.isDirectory();
				}
			};
			mFileList = mPath.list(filter);
		}
		else{
			mFileList= new String[0];
		}
	}
}


